import api from './request'

// 通用API响应类型定义
export interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

// 资源类型定义
export interface Resource {
  id: number
  title: string
  description: string
  fileUrl: string
  fileSize: number
  fileType: string
  userId: number
  nickname: string
  avatar: string
  categoryId: number
  categoryName: string
  downloadCount: number
  likeCount: number
  isLiked: boolean
  createdAt: string
  updatedAt: string
}

// 上传资源 - 根据后端接口文档：/file/uploadResource
export const uploadResource = (formData: FormData) => {
  // 调试：打印 formData 所有字段
  for (const [key, value] of formData.entries()) {
    if (value instanceof File) {
      console.log('formData', key, value.name, value.type, value.size)
    } else {
      console.log('formData', key, value)
    }
  }
  return api.post('/file/uploadResource', formData, {
    timeout: 120000 // 文件上传120秒超时，支持最大100MB文件
  })
}

// 上传图片 - /file/uploadImage
export const uploadImage = (file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  return api.post('/file/uploadImage', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 60000 // 图片上传60秒超时
  })
}

// 分页获取资源列表
export const getResourceList = (params: { pageNum: number; pageSize: number; categoryId?: number; keyword?: string }) => {
  return api.post<ApiResponse<{
    records: Resource[]
    pageNum: number
    pageSize: number
    total: number
    totalPages: number
  }>>('/resources/page', null, { params })
}

// 分页获取指定用户的资源列表（只查正常资源）
export const getUserResourcePage = (params: { pageNum: number; pageSize: number; userId: number }) => {
  const form = new URLSearchParams()
  form.append('pageNum', String(params.pageNum))
  form.append('pageSize', String(params.pageSize))
  form.append('userId', String(params.userId))
  // 直接返回后端原始结构，code/message/data 平级
  return api.post('/resources/user/page', form, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  })
}

// 点赞资源
export const likeResource = (resourceId: number, userId: number) => {
  return api.post<ApiResponse<boolean>>(`/resources/${resourceId}/likes`, null, { params: { userId } })
}

// 取消点赞
export const unlikeResource = (resourceId: number, userId: number) => {
  return api.delete<ApiResponse<boolean>>(`/resources/${resourceId}/likes`, { params: { userId } })
}

// 是否已点赞
export const hasLikedResource = (resourceId: number, userId: number) => {
  return api.get<ApiResponse<boolean>>(`/resources/${resourceId}/likes/has-liked`, { params: { userId } })
}

// 点赞数统计
export const getResourceLikeCount = (resourceId: number) => {
  return api.get<ApiResponse<number>>(`/resources/${resourceId}/likes/count`)
}

// 下载资源
export const downloadResource = (resourceId: number, userId: number) => {
  return api.get(`/file/download`, { params: { resourceId, userId } })
}

// 修改资源状态（0-删除, 1-正常）
export const updateResourceStatus = (resourceId: number, status: number) => {
  const params = new URLSearchParams()
  params.append('resourceId', String(resourceId))
  params.append('status', String(status))
  return api.post<ApiResponse<boolean>>('/resources/status/update', params, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  })
}

// 获取资源统计信息
export const getResourceStats = () => {
  return api.get<ApiResponse<{
    totalCount: number
    contributorCount: number
    totalDownload: number
  }>>('/resources/stats')
}